define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');


    var rebuy = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "复购率") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.switchType();
            this.bindEvent();
            this.initOpenCity();
            this.getRebuyDetails();
            this.downloadCSV();
            this.getSearchDetails();
        },
        /**
         * 不同查询方式
         */
        switchType: function () {
            var self = this;
            if ($('input:radio[name="query_type"]:checked').val() == "city") {
                $(".city-wrap").show();
                $(".search-wrap").hide();
                $(".shop-wrap").hide();
            } else {
                $(".city-wrap").hide();
                $(".search-wrap").show();
                $(".shop-wrap").show();
            }
        },
        /**
         * 获取年份
         * @returns {Array}
         */
        getYears: function () {
            var d = new Date(),
                years = [],
                year = d.getFullYear();
            while (year > 2014) {
                years.unshift(year);
                year--;
            }
            years.reverse();
            return years;
        },
        /**
         * 获取每年周起始
         * @param year
         * @returns {Array}
         */
        getWeeks: function (year) {
            var self = this;
            // weeks[i][0] = '2015-01-01',传输的string
            // weeks[i][1] = '2015.01.01 - 2015.01-07',显示的string
            var weeks = new Array(),
                firstMonday = self.getFirstMonday(year),
                months = self.getDaysPerMonth(year),
                day = firstMonday.getDate(),
                now = new Date(),
                index = 0,
                i;
            var month = now.getMonth() + 1;
            if (year < now.getFullYear()) {//如果不是本年
                month = months.length;
            }
            for (i = 0; i < month; i++) {
                while (day < months[i]) {
                    var start = self.getStringDay(new Date(year, i, day), true),
                        end = self.getStringDay(new Date(year, i, day + 6), true);
                    weeks[index] = new Array();
                    weeks[index][0] = self.getStringDay(new Date(year, i, day));
                    weeks[index][1] = start.substring(5) + ' - ' + end.substring(5);
                    index++;
                    day = day + 7;
                    if (i == now.getMonth() && day > now.getDate()) break;
                }
                day = day - months[i];
            }
            // 干掉2015年5.11之前的日期
            if (year == 2015) {
                weeks.splice(0, 18);
            }
            // reverse weeks!
            weeks.reverse();
            return weeks;
        },
        /**
         * 获取首个周一日期
         * @param year
         * @returns {Date}
         */
        getFirstMonday: function (year) {
            var d = new Date(year, 0, 1),
                day = d.getDay();
            d.setDate((8 - day) % 7 + 1);
            return d;
        },
        /**
         * 获取月份天数
         * @param year
         * @returns {Array}
         */
        getDaysPerMonth: function (year) {
            var months = [],
                i;
            for (i = 0; i < 12; i++) {
                months[i] = this.getMaxDayOfMonth(year, i);
            }
            return months;
        },
        /**
         * 获取每月最大天数
         * @param year
         * @param month
         * @returns {number}
         */
        getMaxDayOfMonth: function (year, month) {
            return 32 - new Date(year, month, 32).getDate();
        },
        /**
         * 转化日期至string
         * @param date
         * @param dot
         * @returns {string}
         */
        getStringDay: function (date, dot) {
            var year = date.getFullYear(),
                month = date.getMonth() + 1,
                day = date.getDate(),
                link = '-';
            if (dot) {
                link = '.';
            }
            if (month < 10) {
                month = '0' + month;
            }
            if (day < 10) {
                day = '0' + day;
            }
            return year + link + month + link + day;
        },
        /**
         * 计算周长度
         * @param start
         * @param end
         * @returns {Number}
         */
        countWeekLength: function (start, end) {
            var startArr = start.split('-'),
                endArr = end.split('-'),
                startDate = new Date(startArr[0], startArr[1] - 1, startArr[2] - 0),
                endDate = new Date(endArr[0], endArr[1] - 1, endArr[2] - 0),
                weekLength = parseInt((endDate - startDate) / (1000 * 86400 * 7) + 1);
            return weekLength;
        },
        /**
         * 判断 date
         * @param date
         * @returns {boolean}
         */
        judgeDate: function (date) {
            var now = new Date(),
                arr = date.split('-'),
                d = new Date(arr[0], arr[1] - 1, arr[2] - 0),
                stamp = now - d;
            return stamp >= 0 ? true : false;
        },
        /**
         * select监听
         * @param els
         */
        changeSelectStatus: function (els) {
            var self = this;
            // 渲染年份对应自然周
            var renderYears = function () {
                var start = $('.start-year'),
                    end = $('.end-year'),
                    years = self.getYears(),
                    tpl = '',
                    i;
                for (i = 0; i < years.length; i++) {
                    tpl += '<option value="' + years[i] + '">' + years[i] + '年</option>';
                }
                start.html(tpl);
                end.html(tpl);
            }
            renderYears();
            var renderWeeks = function (el, val) {
                var weeks = self.getWeeks(val),
                    tpl = '<option value="0">-请选择自然周-</option>';
                weeks.forEach(function (el, i) {
                    tpl += '<option value="' + el[0] + '">' + el[1] + '</option>';
                });
                el.html(tpl);
            }
            renderWeeks($('.start-week'), $('.start-year').val());
            renderWeeks($('.end-week'), $('.end-year').val());
            var removeWeeks = function (el) {
                var selects = el.nextElementSibling,
                    tpl = '<option value="0">-请选择自然周-</option>';
                el.html(tpl);
            }
            var switchWeeks = function (els) {
                var startYear = els[0],
                    startWeek = els[1],
                    endYear = els[2],
                    endWeek = els[3];
                if (endYear.val() != 0 && endYear.val() < startYear.val()) {
                    CRM.showDialog("结束年份不得小于开始年份！");
                    return;
                }
                if (endWeek.val() <= startWeek.val() && endWeek.val() != 0) {
                    CRM.showDialog("结束自然周必须大于开始自然周！");
                }
            }

            var onSelectChange = function () {
                var self = $(this),
                    val = this.value;
                if (self.attr("id") == "start-week" || self.attr("id") == "end-week") {
                    switchWeeks(els);
                    return;
                }
                if (val != 0) {
                    renderWeeks($("." + $(this).attr("child_class")), val);
                } else {
                    removeWeeks(self);
                }
                switchWeeks(els);
            }
            var i;
            for (i = 0; i < els.length; i++) {
                els[i].on('change', onSelectChange);
            }
        },
        //初始化开放城市
        initOpenCity: function () {
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl('/shop/city/queryOpenCity'),
                "dataType": "json",
                contentType: "application/json",
                "data": JSON.stringify({
                    "operator": $.cookie('_uk')
                }),
                "success": function (req) {
                    if (req.status) {
                        $("#rebuy-city").html("");
                        $("#rebuy-city").append("<option value='0'>-请选择城市-</option>");
                        for (var length in req.entry) {
                            $("#rebuy-city").append("<option value='" + req.entry[length].regionId + "'>" + req.entry[length].city + "</option>");
                        }
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 查询开始
         */
        getRebuyDetails: function () {
            var self = this,
                submitBtn = document.querySelector('.rebuy-submit a'),
                clickToken = true,
                validateData = function (params) {
                    if (params.startweek == 0) {
                        CRM.showDialog('请选择开始日期');
                        clickToken = true;
                        submitBtn.innerHTML = '查询';
                        return;
                    }
                    if (params.endweek == 0) {
                        CRM.showDialog('请选择结束日期');
                        clickToken = true;
                        submitBtn.innerHTML = '查询';
                        return;
                    }
                    if (self.countWeekLength(params.startweek, params.endweek) > 16) {
                        CRM.showDialog('查找周期不得超过16周');
                        clickToken = true;
                        submitBtn.innerHTML = '查询';
                        return;
                    }
                    if (params.cityids == 0) {
                        CRM.showDialog('请选择城市');
                        clickToken = true;
                        submitBtn.innerHTML = '查询';
                        return;
                    }
                    if (params.shopids == '') {
                        CRM.showDialog('请选择店铺');
                        clickToken = true;
                        submitBtn.innerHTML = '查询';
                        return;
                    }
                    return true;
                },
                getRebuyData = function (url, params) {
                    CRM.request({
                        "type": 'get',
                        "url": url,
                        "dataType": "json",
                        contentType: "application/json",
                        "data": params,
                        "success": function (req) {
                            //req = eval(req);
                            clickToken = true;
                            submitBtn.innerHTML = '查询';
                            if (req.status) {
                                var type;
                                if ($('input:radio[name="query_type"]:checked').val() == "city") {
                                    type = 1;
                                } else {
                                    type = 0;
                                }
                                var keys = Object.keys(req.entry);
                                if (keys.length > 0) {
                                    self.renderTable(req.entry, params.startweek, params.endweek, type);
                                } else {
                                    CRM.showDialog('复购率查找结果为空');
                                }
                            } else {
                                CRM.showDialog(req.message);
                            }
                        },
                        "error": function () {
                            clickToken = true;
                            submitBtn.innerHTML = '查询';
                            CRM.showDialog('请求服务异常!');
                        }
                    });
                },
                getSubmitData = function () {
                    if (clickToken == false) {
                        return;
                    }
                    clickToken = false;
                    submitBtn.innerHTML = '查询中...';
                    var
                        startWeek = $('.start-week').val(),
                        endWeek = $('.end-week').val(),
                        userId = $.cookie('_uk'),
                        cityIds = $('.rebuy-city').val();
                    var
                        typeIds = document.querySelectorAll('.rebuy-order-type'),
                        typeId,
                        i;
                    for (i = 0; i < typeIds.length; i++) {
                        if (typeIds[i].checked == true) {
                            typeId = typeIds[i].value;
                            break;
                        }
                    }
                    var shopIds = [];
                    $("input[name='shops']:checked").each(function () {
                        shopIds.push(this.value);
                    });
                    shopIds = shopIds.join(',');
                    var params = {
                            'startweek': startWeek,
                            'endweek': endWeek,
                            'userid': userId,
                            'typeid': typeId,
                            'cityids': cityIds,
                            'shopids': shopIds
                        },
                        url;
                    if ($('input:radio[name="query_type"]:checked').val() == "city") {
                        url = CRM.getOuterUrl('/purchase/stat/m/city/purchase/list');
                        delete params.shopids;
                    } else {
                        url = CRM.getOuterUrl('/purchase/stat/m/shop/purchase/list');
                        delete params.cityids;
                    }
                    var flag = validateData(params);
                    if (flag && params) {
                        getRebuyData(url, params);
                    }
                };
            submitBtn.addEventListener('click', getSubmitData, false);
        },
        /**
         *  下周CSV
         */
        downloadCSV: function () {
            var self = this,
                downloadBtn = document.querySelector('.rebuy-download'),
                validateData = function (params) {
                    if (params.startweek == 0) {
                        CRM.showDialog('请选择开始日期');
                        return;
                    }
                    if (params.endweek == 0) {
                        CRM.showDialog('请选择结束日期');
                        return;
                    }
                    if (self.countWeekLength(params.startweek, params.endweek) > 16) {
                        CRM.showDialog('查找周期不得超过16周');
                        return;
                    }
                    if (params.cityids == 0) {
                        CRM.showDialog('请选择城市');
                        clickToken = true;
                        return;
                    }
                    if (params.shopids == '') {
                        CRM.showDialog('请选择店铺');
                        clickToken = true;
                        return;
                    }
                    return true;
                },
                downloadAction = function (url) {
                    if (url) window.open(url, '_blank');
                },
                getDownloadUrl = function (url, params) {
                    var link = '';
                    for (var i in params) {
                        link += '&' + i + '=' + params[i];
                    }
                    return url + '?' + link.substr(1);
                },
                getDownloadData = function () {
                    var
                        startWeek = document.querySelector('.start-week').value,
                        endWeek = document.querySelector('.end-week').value,
                        userId = $.cookie('_uk'),
                        cityIds = document.querySelector('.rebuy-city').value;
                    var
                        typeIds = document.querySelectorAll('.rebuy-order-type'),
                        typeId,
                        i;
                    for (i = 0; i < typeIds.length; i++) {
                        if (typeIds[i].checked == true) {
                            typeId = typeIds[i].value;
                            break;
                        }
                    }
                    var shopIds = [];
                    $("input[name='shops']:checked").each(function () {
                        shopIds.push(this.value);
                    });
                    shopIds = shopIds.join(',');
                    var
                        params = {
                            'startweek': startWeek,
                            'endweek': endWeek,
                            'userid': userId,
                            'typeid': typeId,
                            'cityids': cityIds,
                            'shopids': shopIds
                        },
                        url;
                    if ($('input:radio[name="query_type"]:checked').val() == "city") {
                        url = CRM.getOuterUrl('/purchase/stat/m/city/purchase/download');
                        delete params.shopids;
                    } else {
                        url = CRM.getOuterUrl('/purchase/stat/m/shop/purchase/download');
                        delete params.cityids;
                    }
                    var flag = validateData(params);
                    if (flag && params) {
                        var downloadUrl = getDownloadUrl(url, params);
                        downloadAction(downloadUrl);
                    }
                };
            downloadBtn.addEventListener('click', getDownloadData, false);
        },
        /**
         * 渲染table
         * @param data
         * @param start
         * @param end
         * @param type
         */
        renderTable: function (data, start, end, type) {
            var self = this,
                shopKeys = Object.keys(data),
                sortShops = function (data, keys) {
                    var
                        arr = [],
                        i;
                    for (i = 0; i < keys.length; i++) {
                        if (data[keys[i]][0] !== undefined) {
                            arr.push(keys[i]);
                        }
                    }
                    ;
                    return arr;
                },
                renderWeekData = function (start, end) {
                    var
                        weeks = [],
                        i,
                        weekLength = self.countWeekLength(start, end);
                    for (i = 0; i < weekLength; i++) {
                        var
                            startArr = start.split('-'),
                            startDate = new Date(startArr[0], startArr[1] - 1, startArr[2] - 0),
                            from = new Date(startDate.getTime() + i * (1000 * 86400 * 7)),
                            to = new Date(from.getTime() + 1000 * 86400 * 6),
                            whole = self.getStringDay(from, true).substring(5) + ' - ' + self.getStringDay(to, true).substring(5);
                        weeks.push(whole);
                    }
                    return weeks;
                },
                weeks = renderWeekData(start, end);
            shopKeys = sortShops(data, shopKeys);
            var shopInfo = [];
            if (type == 0) {
                $.each(shopKeys,function(index, item){
                    shopInfo.push(self.getShopInfo(item));
                })
            }
            self.renderTableV2(shopInfo, data, weeks, shopKeys, type);
        },
        /**
         * 渲染table2
         * @param info
         * @param data
         * @param weeks
         * @param shopKeys
         * @param type
         */
        renderTableV2: function (info, data, weeks, shopKeys, type) {
            var
                tableWrap = document.querySelector('.table-wrap'),
                tpl = '',
                i, j, k, l, count, rate, name;
            // 循环店铺
            for (i = 0; i < shopKeys.length; i++) {
                tpl += '<table class="rebuy-table">';
                tpl += '<thead><tr>';
                tpl += '<th>城市</th>';
                // shop附加
                if (type == 0) {
                    tpl += '<th>主管</th>';
                    tpl += '<th>小二</th>';
                    tpl += '<th>店铺</th>';
                }
                tpl += '<th>周次</th>';
                // 循环row日期
                for (j = 0; j < weeks.length; j++) {
                    tpl += '<th>' + weeks[j] + '</th>';
                }
                tpl += '</tr></thead>';
                tpl += '<tbody>';
                // 循环col日期，shopName/cityName
                for (k = 0; k < weeks.length; k++) {
                    if (k % 2 == 0)
                        tpl += '<tr>';
                    else
                        tpl += '<tr class="even">';
                    if (k == 0 && type == 0) {
                        name = data[shopKeys[i]][0]['shopName'];
                        tpl += '<td rowspan="' + weeks.length + '" class="city-name">' + info[i].city + '</td>';
                        if(info[i].xiaoerName){
                            tpl += '<td rowspan="' + weeks.length + '" class="manainfo[i].xiaoerManagerNameger-name">' + info[i].xiaoerName + '</td>';
                        }else{
                            tpl += '<td rowspan="' + weeks.length + '" class="manainfo[i].xiaoerManagerNameger-name"></td>';
                        }
                        if(info[i].xiaoerName){
                            tpl += '<td rowspan="' + weeks.length + '" class="xiaoer-name">' + info[i].xiaoerName + '</td>';
                        }else{
                            tpl += '<td rowspan="' + weeks.length + '" class="xiaoer-name"></td>';
                        }
                        tpl += '<td rowspan="' + weeks.length + '" class="shop-name">' + name + '</td>';
                    }
                    if (k == 0 && type == 1) {
                        name = data[shopKeys[i]][0]['cityName'];
                        tpl += '<td rowspan="' + weeks.length + '" class="city-name">' + name + '</td>';
                    }
                    // 循环counts
                    for (l = 0; l < weeks.length + 1; l++) {
                        if (l == 0) {
                            tpl += '<td>' + weeks[k] + '</td>';
                        } else {
                            if (l < k + 1) {
                                tpl += '<td></td>';
                            }
                            if (l == k + 1) {
                                count = data[shopKeys[i]][k]['relativeCount'];
                                tpl += '<td class="selected-customer">' + count + '</td>';
                            }
                            if (l > k + 1) {
                                rate = (data[shopKeys[i]][k]['purchase'][l - k - 2]['rate'] * 100).toFixed(1) + '%';
                                tpl += '<td class="selected-rebuy-percent">' + rate + '</td>';
                            }
                        }
                    }
                    tpl += '</tr>';
                }
                tpl += '</tbody>';
                tpl += '</table>';
            }

            tableWrap.innerHTML = tpl;
        },
        /**
         * 搜索店铺
         */
        getSearchDetails: function () {
            var self = this,
                searchBtn = document.querySelector('.rebuy-search a'),
                shopBox = document.querySelector('.rebuy-shop-container'),
                getSearchResult = function () {
                    var params = document.querySelector('.shop-search').value.trim();
                    if (params == '') {
                        CRM.showDialog('手机号或者店铺名不能为空');
                        return;
                    }
                    var _url = CRM.getOuterUrl('/shop/shop/queryShopByName');
                    var dataString = JSON.stringify({
                        "shopName": params,
                        "operator": $.cookie('_uk'),
                        "pageBegin": 1,
                        "pageSize": 50
                    });
                    var partten = /^1[3,5,7,8,9]\d{9}$/;
                    if (partten.test(params)) {
                        params = self.getUserInfo(params);
                        _url = CRM.getOuterUrl('/shop/shop/queryShopByXiaoerId');
                        dataString = JSON.stringify({
                            "xiaoerId": params,
                            "operator": $.cookie('_uk'),
                            "pageBegin": 1,
                            "pageSize": 50
                        });
                    }
                    CRM.request({
                        "type": 'POST',
                        "url": _url,
                        "dataType": "json",
                        contentType: "application/json",
                        "data": dataString,
                        "success": function (req) {
                            if (req.status) {
                                var rs = req.entry, tpl = "<p>暂无数据，请在上方搜索框输入进行搜索</p>";
                                if (rs) {
                                    tpl = '<table>';
                                    for (i = 0; i < rs.length; i++) {
                                        if (i % 5 == 0) tpl += '<tr>';
                                        tpl += '<td class="rebuy-shop-item" data-val="' + rs[i].id + '" title="' + rs[i].shopName + '">' +
                                            '<label class="checkbox-inline"><input type="checkbox" name="shops" class="rebuy-order-type" value="' + rs[i].id + '">'
                                            + rs[i].shopName + '</label></td>';
                                        if (i % 5 == 4) tpl += '</tr>';
                                        if (i == rs.length && i % 5 != 4) tpl += '</tr>';
                                    }
                                    tpl += '</table>';
                                }
                                shopBox.innerHTML = tpl;
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                };
            searchBtn.addEventListener('click', getSearchResult, false);
        },
        /**
         * 手机号码获取用户信息
         * @param mobile
         */
        getUserInfo: function (mobile) {
            var _userId;
            CRM.request({
                url: CRM.getOuterUrl('/member/getUserbyMobile.do?mobile=' + mobile),
                type: 'get',
                async: false,
                success: function (data) {
                    if (data.status) {
                        _userId = data.entry.userId;
                    }
                }
            });
            return _userId;
        },
        /**
         * 获取店铺信息
         *
         * @param shopId
         * @returns {*}
         */
        getShopInfo: function (shopId) {
            var _hopInfo,
                dataString = JSON.stringify({
                    "id": shopId,
                    "operator": $.cookie('_uk')
                });
            CRM.request({
                url: CRM.getOuterUrl('/shop/shop/queryShopById'),
                type: 'post',
                async: false,
                dataType: "json",
                contentType: "application/json",
                data: dataString,
                success: function (data) {
                    if (data.status) {
                        _hopInfo = data.entry;
                    }
                }
            });
            return _hopInfo;
        },
        bindEvent: function () {
            var self = this;
            $("#query_type_city").on('click', self.switchType);
            $("#query_type_shop").on('click', self.switchType);
            var clickToken,
                startYear = $('.start-year'),
                startWeek = $('.start-week'),
                endYear = $('.end-year'),
                endWeek = $('.end-week'),
                els = [startYear, startWeek, endYear, endWeek];
            self.changeSelectStatus(els);
        }
    };

    rebuy.init();
});